<template>
	<wsPage :title="$t('shop.editProduct')">
		<div slot="page_operate">
			<Button type="ghost" @click="goBack"><Icon type="ios-arrow-back"></Icon><span>{{$t('shop.back')}}</span></Button>
		</div>

		<wsPanel>
			<template slot="panel_head_title">{{$t('shop.editProduct')}}</template>
			<div slot="panel_body" class="ws-form-div">
				<div class="ws-form-div-form" v-show="!result.ok">
					<Steps :current="current">
						<!--<Step title="选择商品分类"></Step>-->
						<Step :title="$t('shop.basicInforProd')"></Step>
						<Step :title="$t('shop.improveProdDetails')"></Step>
					</Steps>
					<div class="step-data">
						<!--<div v-show="current == 0">
							<div class="wareSort clearfix">
								<ul v-for="(group, groupIndex) in form0.groups">
									<li v-for="(item, itemIndex) in group.datas" :class="{'active': itemIndex == group.active}" @click="next(group, groupIndex, item, itemIndex)">
										<a>{{item.label}}</a>
									</li>
								</ul>
							</div>
							<div class="selectedSort">
								<b>你当前选择的商品类别是:</b><i v-text="currentCategoryLabel"></i>
							</div>
							<div class="wareSortBtn">
								<Button type="primary" @click="firstNextStep" :disabled="!form0.isLastLevel">下一步</Button>
							</div>
						</div>-->
						<div v-show="current == 1">
							<Alert show-icon>
								{{$t('shop.OperationPrompt')}}
								<template slot="desc">
									<p>1.{{$t('shop.OperationPromptOne')}}</p>
									<p>2.{{$t('shop.OperationPromptTwo')}}</p>
								</template>
							</Alert>
							<Form ref="form1" :model="form1.model" :rules="form1.rules" :label-width="150">
								<FormItem :label="$t('shop.productCategory')" required>
									<span v-text="categoryFullPath"></span>
								</FormItem>
								<FormItem :label="$t('shop.productname')" prop="name">
									<Input v-model="form1.model.name" autofocus></Input>
								</FormItem>
								<FormItem :label="$t('shop.Releasetype')" prop="promotionStatus">
									<RadioGroup v-model="form1.model.promotionStatus">
										<Radio :label="0">{{$t('shop.newest')}}</Radio>
										<Radio :label="1">{{$t('shop.discount')}}</Radio>
									</RadioGroup>
								</FormItem>
								<FormItem :label="$t('shop.salesType')" prop="saleType">
									<RadioGroup v-model="form1.model.saleType">
										<Radio :label="1">{{$t('shop.Spot')}}</Radio>
										<Radio :label="2">{{$t('shop.Presale')}}</Radio>
									</RadioGroup>
								</FormItem>
								<FormItem :label="$t('shop.makeFlag')" prop="makeFlag">
									<RadioGroup v-model="form1.model.makeFlag">
										<Radio :label="1">{{$t('shop.yes')}}</Radio>
										<Radio :label="0">{{$t('shop.no')}}</Radio>
									</RadioGroup>
								</FormItem>
								<FormItem :label="$t('shop.supportList')" prop="isReturnsExchange">
									<RadioGroup v-model="form1.model.isReturnsExchange">
										<Radio :label="1">{{$t('shop.yes')}}</Radio>
										<Radio :label="0">{{$t('shop.no')}}</Radio>
									</RadioGroup>
								</FormItem>
								<FormItem :label="$t('shop.Brand')" prop="brandId">
									<Select v-model="form1.model.brandId" filterable>
										<Option v-for="item in form1.fields.brands" :value="item.id" :key="item.id">{{ item.name }}</Option>
									</Select>
								</FormItem>
								<FormItem :label="$t('shop.languageVersion')" prop="languageCode">
									<Select v-model="form1.model.languageCode">
										<Option v-for="item in form1.fields.languages" :value="item.code" :key="item.code">{{ item.motherTongue }}({{item.english}})</Option>
									</Select>
								</FormItem>
							</Form>
							<!--sku---->
							<Form ref="form2" :model="form2.model" :rules="form2.rules" :label-width="150">
								<FormItem :label="specItem.page.name" v-for="(specItem, specIndex) in form2.specs" required>
									<CheckboxGroup v-model="form2.model.values[specIndex]" @on-change="specItemChange(specItem, specIndex)">
										<Checkbox :label="specValueItem" v-for="(specValueItem, specValueIndex) in specItem.values">
											<span v-text="specValueItem"></span>
										</Checkbox>
									</CheckboxGroup>
									<Input size="small" :placeholder="$t('shop.newValue')" style="width: 150px;" v-model="form2.model.inputValues[specIndex]">
									<Button size="small" slot="append" @click="addSpecValue(specIndex)">{{$t('shop.addTo')}}</Button>
									</Input>
								</FormItem>
								<FormItem label="SKU" prop="name" required>
									<ws-table :data="form2.table.datas" ref="skutable">
										<ws-table-column align="center" width="100" :prop="item.key" :label="item.title" v-for="item in form2.table.skuColumns"></ws-table-column>
										<ws-table-column align="center" :label="isUpNew ? $t('shop.newPrice') : $t('shop.discountPrice')" width="100">
											<template slot-scope="scope">
												<InputNumber @on-blur="priceFormatter(scope.row)" v-model="scope.row.price"></InputNumber>
											</template>
										</ws-table-column>
										<ws-table-column align="center" :label="$t('shop.OriginalPrice')" v-if="!isUpNew" width="100">
											<template slot-scope="scope">
												<InputNumber @on-blur="marketPriceFormatter(scope.row)" v-model="scope.row.marketPrice"></InputNumber>
											</template>
										</ws-table-column>
										<ws-table-column align="center" :label="$t('shop.stock')" v-if="isPresentSale" width="100">
											<template slot-scope="scope">
												<InputNumber :precision="0" v-model="scope.row.stock"></InputNumber>
											</template>
										</ws-table-column>
										<ws-table-column align="center" :label="$t('shop.memberPrice')" width="100">
											<template slot-scope="scope">
												<InputNumber :precision="0" v-model="scope.row.memberPrice"></InputNumber>
											</template>
										</ws-table-column>
										<ws-table-column align="center" :label="$t('shop.Setting')" width="100">
											<template slot-scope="scope">
												<Tooltip :content="$t('shop.settingApplies')" placement="top" transfer>
													<Button type="text" @click="skuSettingToAll(scope.$index)">{{$t('shop.application')}}</Button>
												</Tooltip>
											</template>
										</ws-table-column>
									</ws-table>
								</FormItem>
							</Form>
							<div class="wareSortBtn">
								<!--<Button type="primary" @click="current = 0">上一步</Button>-->
								<Button type="primary" @click="secondNextStep">{{$t('shop.nextStep')}}</Button>
							</div>
						</div>
						<div v-show="current == 2">
							<Alert show-icon>
								{{$t('shop.OperationPrompt')}}
								<template slot="desc">
									<p>1.{{$t('shop.OperationPromptThree')}}</p>
									<p>2.{{$t('shop.OperationPromptFour')}}</p>
								</template>
							</Alert>
							<Form ref="form4" :model="form4.model" :rules="form4.rules" :label-width="100">
								<FormItem :label="$t('shop.prodPicture')" required>
									<ul class="img-list">
										<li v-for="(item,index) in 5" >
											<div @click="removePic(index)" style="background:rgba(255,255,255,0.3);font-size:26px;height:30px;width:30px;border-radius:25px;position:absolute;top:10px;right:10px;z-index:5;text-align:center;color:black;line-height:30px;cursor:pointer;" v-show="form4.tmpPics[index]">X</div>
											<ws-upload-cos ref="picUpload" :loopIndex="index" catelog="users" :show-upload-list="false" :format="['jpg','jpeg','png']" :max-size="2048" :on-success="picUploadSuccess" type="drag" style="width:200px;height: 200px" :auto-upload="false" :on-file-list="uploadFileList">
												<div style="width:200px;line-height: 200px;height: 200px;" class="ws-middle">
													<img :src="form4.tmpPics[index]" width="200px" height="200px" v-if="form4.tmpPics[index]"></img>
												</div>
												<div class="primary-pic"><span>{{0 == index ? $t('shop.prodMainPic') : $t('shop.prodDetailPic')}}</span></div>
											</ws-upload-cos>
										</li>
									</ul>
								</FormItem>
								<FormItem :label="$t('shop.productDetails')" required>
									<wsEditor :auto-init="form3.editor.whetherInit" :default-msg="form3.model.wDesc" :config="form3.editor.config" ref="ue"></wsEditor>
								</FormItem>
							</Form>
							<div class="wareSortBtn">
								<Button type="primary" @click="current = 1">{{$t('shop.Previous')}}</Button>
								<Button type="primary" @click="saveAndUpProduct">{{$t('shop.UpdateAndPublish')}}</Button>
								<Button type="primary" @click="saveProduct">{{$t('shop.UpdateDraft')}}</Button>
							</div>
						</div>
					</div>
				</div>

				<!--操作成功-->
				<div class="ws-form-div-form" v-show="result.ok" style="text-align: center;">
					<div style="padding-bottom: 25px;">
						<p style="font-size: 20px;padding-bottom: 10px;">{{$t('shop.updateProdSuccess')}}</p>
						<p>{{$t('shop.needFollowing')}}</p>
					</div>
					<div>
						<Button @click="clearAll">{{$t('shop.continueAddProd')}}</Button>
						<Button @click="goBack">{{$t('shop.backProductList')}}</Button>
					</div>
				</div>

			</div>
		</wsPanel>
	</wsPage>
</template>

<script>
	import Util from '../../../common/util.js';
	import Common from '../../../common/common.js';
	import DescartesUtils from './DescartesUtils.js';
	import FileUtil from '../../../common/file.js';
	export default {
		data() {
			return {
				current: 0, //当前步骤
				isStepOver: false, //是否已经配置规格
				preCategoryId: null, //上一次选择的商品类目
				categoryFullPath: '', //服务目录路径
				//类目选择
				form0: {
					groups: [], //组
					categoryTree: [], //服务目录树
					indexPaths: [],
					isLastLevel: false, //是否为最后一级
					labels: [], //选中的标题
					currentCatelogId: null //当前选中的目录编号
				},
				form1: {
					model: {
						id: null, //商品编号
						brandId: '', //品牌
						name: '',
						promotionStatus: 0, //商品类别 0.上新 1.折扣
						languageCode: '',
						saleType: 1, //1.现货 2.预售
						brandName: '',
						makeFlag:0, //1.订制 0.非定制
						isReturnExchange:0  //1.支持退货 0.不支持退货
					},
					fields: {
						languages: [], //语言
						brands: [], //品牌
						searchLoading: false
					},
					rules: {
						name: [{
								required: true,
								message: '请输入商品名称',
								trigger: 'blur'
							},
							{
								max: 128,
								message: '商品名称太长',
								trigger: 'blur'
							}
						],
						languageCode: [{
							required: true,
							message: '商品发布语言版本必须选择'
						}],
						brandId: [{
							required: true,
							message: '必须选择商品所属品牌'
						}],
						promotionStatus: [{
							required: true,
							message: '发布类型必须选择'
						}],
						saleType: [{
							required: true,
							message: '销售类型必须选择'
						}],
						makeFlag: [{
							required: true,
							message: '是否订制商品必须选择'
						}],
						isReturnExchange: [{
							required: true,
							message: '是否支持退换货必须选择'
						}]
					},

				},
				//规格表单
				form2: {
					model: {
						values: [], //checkbox 选中值
						inputValues: [] //输入框的值
					},
					rules: {
						values: [{
							required: true,
							type: 'array',
							min: 1,
							message: '至少选择一个爱好',
							trigger: 'change'
						}, ]
					},
					table: {
						skuColumns: [],
						datas: []
					},
					//规格数据
					specs: []
				},
				form3: {
					model: {
						wDesc: ''
					},
					//文本编辑器
					editor: {
						config: {
							initialFrameWidth: null,
							initialFrameHeight: 350
						},
						whetherInit: false //是否初始化
					}
				},
				//商品图片列表
				form4: {
					tmpPics: [],//base64语言
					files: [], //文件列表
					fileNames: [], //文件名记录文件添加顺序
					updateTmpPics: [], //更新记录
					num: 0,
					imgConfig: { //图片配置

					}
				},
				result: {
					ok: false
				}
			}
		},
		computed: {
			/**
			 * 当前选中的商品目录
			 */
			currentCategoryLabel() {
				let categorys_ = this.form0.labels;
				let str_ = '';
				for(let i = 0; i < categorys_.length; i++) {
					if(0 != i) {
						str_ += '>';
					}
					str_ += categorys_[i];
				}
				return str_;
			},
			/**
			 * 是否上新商品
			 */
			isUpNew() {
				return this.form1.model.promotionStatus == 0;
			},
			/**
			 * 是否预售
			 */
			isPresentSale() {
				return this.form1.model.saleType == 1;
			},
			/**
			 * 是否显示上传按钮
			 */
			showPicUpload() {
				return this.form4.files.length < 5;
			},
			/**
			 * 商品图片数量
			 */
			picCount() {
				let tmpFiles = this.form4.tmpPics;
				let picCount = 0;
				for(let i = 0; i < tmpFiles.length; i++) {
					if(tmpFiles[i]) {
						picCount++;
					}
				}
				return picCount;
			},
			/**
			 * 商品图片数量
			 */
			picNewCount() {
				let tmpFiles = this.form4.tmpPics;
				let picCount = 0;
				for(let i = 0; i < tmpFiles.length; i++) {
					if(tmpFiles[i] && tmpFiles[i].indexOf('data:') == 0) {
						picCount++;
					}
				}
				return picCount;
			}			
		},
		mounted() {
			this.form1.model.id = this.$route.query.productId;
			this.init();
			// 当前选择的语言版本
			let getCurrentLanguage=localStorage.getItem('currentLanguage');
			this.$i18n.locale=getCurrentLanguage;

			if(getCurrentLanguage=='en'){
				this.form1.rules={
					name: [{
								required: true,
								message: 'Please enter the product name',
								trigger: 'blur'
							},
							{
								max: 128,
								message: 'Product name is too long',
								trigger: 'blur'
							}
						],
						languageCode: [{
							required: true,
							message: 'Product release language version must be selected'
						}],
						brandId: [{
							required: true,
							message: 'Must choose the brand of the product'
						}],
						promotionStatus: [{
							required: true,
							message: 'Release type must be selected'
						}],
						saleType: [{
							required: true,
							message: 'Sales type must be selected'
						}]
				}
			}else if(getCurrentLanguage=='it'){
				this.form1.rules={
					name: [{
								required: true,
								message: 'Si prega di inserire il nome del prodotto',
								trigger: 'blur'
							},
							{
								max: 128,
								message: 'Il nome del prodotto è troppo lungo',
								trigger: 'blur'
							}
						],
						languageCode: [{
							required: true,
							message: 'La versione della lingua di rilascio del prodotto deve essere selezionata'
						}],
						brandId: [{
							required: true,
							message: 'Deve scegliere la marca del prodotto'
						}],
						promotionStatus: [{
							required: true,
							message: 'Il tipo di rilascio deve essere selezionato'
						}],
						saleType: [{
							required: true,
							message: 'Il tipo di vendita deve essere selezionato'
						}]
				}
			}

		},
		methods: {
			init() {
				this.initGoods();
				this.loadLanguage();
				this.initBrands();
			},
			/**
			 * 初始化商品信息
			 */
			initGoods() {
				let _this = this;
				let productId = this.form1.model.id;
				this.axios.get('/ws/v2/ms/product/' + productId).then(response => {
					var res = response.data;
					var resMeta = res.meta;
					if(0 == resMeta.code) {
						_this.buildGoodsInfo(res.data);
					} else {
						if(_this.$i18n.locale=='zh'){
							_this.$Message.warning('商品信息加载失败,请重试:' + resMeta.message);
						}else if(_this.$i18n.locale=='en'){
							_this.$Message.warning('Product information failed to load, please try again:' + resMeta.message);
						}else if(_this.$i18n.locale=='it'){
							_this.$Message.warning('Impossibile caricare le informazioni sul prodotto, riprova:' + resMeta.message);
						}
						
					}
				});
			},
			/**
			 * 删除商品
			 */
			delGoods(index){
				console.log(index);
				console.log(this.form4.tmpPics);
				if(this.form4.tmpPics[index] != ''){
					this.form4.tmpPics[index] = '';
				}
			},
			/**
			 * 构建商品信息
			 */
			buildGoodsInfo(data) {
				this.current =  1; //当前步骤
				this.isStepOver = false; //是否已经配置规格
				this.categoryFullPath = data.categoryFullPath;
				this.form0.currentCatelogId = data.product.categoryId;//当前选中的目录编号
				this.form1.model.id = data.product.id; //商品编号
				this.form1.model.brandId = data.product.brandId;//品牌
				this.form1.model.name = data.product.name;//商品名称
				this.form1.model.promotionStatus = data.product.promotionStatus;//商品类别 0.上新 1.折扣
				this.form1.model.languageCode = data.product.languageCode;//语言类型
				this.form1.model.saleType = data.product.saleType;//1.现货 2.预售
				this.form1.model.makeFlag = data.product.makeFlag;//1.订制 0.非定制
				this.form1.model.isReturnsExchange = data.product.isReturnsExchange;//1.支持 0.不支持
				this.form3.model.wDesc = data.product.wDesc;//商品描述
				this.form1.model.brandName= data.product.brandName;//品牌名称
				let picList = data.picList;
				console.log(picList)
				for(let i = 0; i < picList.length; i++) {
					let pic_ = picList[i];
					this.form4.tmpPics.push(pic_);
				}
				//加载规格
				this.specTrigger(data);
			},
			/**
			 * 初始化品牌列表
			 */
			initBrands() {
				const _this = this;
				this.form1.fields.searchLoading = true;
				this.axios.get('/ws/ops/brands').then(response => {
					var res = response.data;
					var resMeta = res.meta;
					if(0 == resMeta.code) {
						_this.form1.fields.brands = res.data;
					} else {
						if(_this.$i18n.locale=='zh'){
							_this.$Message.warning('初始品牌失败:' + resMeta.message);
						}else if(_this.$i18n.locale=='en'){
							_this.$Message.warning('Initial brand failure:' + resMeta.message);
						}else if(_this.$i18n.locale=='it'){
							_this.$Message.warning('Fallimento del marchio iniziale:' + resMeta.message);
						}
						
					}
					this.form1.fields.searchLoading = false;
				});
			},
			/**
			 * 初始化品牌列表
			 */
			initBrandSearch(keyword) {
				const _this = this;
				this.form1.fields.searchLoading = true;
				this.axios.get('/ws/ops/brands/search?keyword=' + keyword).then(response => {
					var res = response.data;
					var resMeta = res.meta;
					if(0 == resMeta.code) {
						_this.form1.fields.brands = res.data;
					} else {
						if(_this.$i18n.locale=='zh'){
							_this.$Message.warning('初始品牌失败:' + resMeta.message);
						}else if(_this.$i18n.locale=='en'){
							_this.$Message.warning('Initial brand failure:' + resMeta.message);
						}else if(_this.$i18n.locale=='it'){
							_this.$Message.warning('Fallimento del marchio iniziale:' + resMeta.message);
						}						
					}
					this.form1.fields.searchLoading = false;
				});
			},
			/**
			 * 品牌搜索
			 */
			brandRemoteSearch(query) {
				if(!Util.vad.isBlank(query)) {
//					this.initBrandSearch(query);
				}
			},
			/**
			 * 加载商品语言
			 */
			loadLanguage() {
				const _this = this;
				this.axios.get('/ws/ops/v2/languages').then(response => {
					let res = response.data;
					if(0 === res.meta.code) {
						if(res.data.length > 0) {
							_this.form1.fields.languages = res.data;
						}
					} else {
						let message_ = res.meta.message;
						if(_this.$i18n.locale=='zh'){
							_this.$Message.warning('加载语言失败:' + message_);
						}else if(_this.$i18n.locale=='en'){
							_this.$Message.warning('Loading language failed:' + message_);
						}else if(_this.$i18n.locale=='it'){
							_this.$Message.warning('Caricamento della lingua fallito:' + message_);
						}
						
					}
				});
			},
			/**
			 * 步骤二触发(规格触发)
			 */
			specTrigger(product_) {
				let currCategoryId = this.form0.currentCatelogId;
				let _this = this;
				this.loadCategoryPropertys(currCategoryId, function(data) {
					_this.buildSkuProperty(product_, data);
				});
			},
			/**
			 * 加载商品类型的参数
			 */
			loadCategoryPropertys(categoryId, callback) {
				const _this = this;
				this.axios.get('/ws/ops/v2/category/' + categoryId + '/propertys').then(response => {
					var res = response.data;
					var resMeta = res.meta;
					if(0 == resMeta.code) {
						callback(res.data);
					} else {
						if(_this.$i18n.locale=='zh'){
							_this.$Message.warning('加载规格数据失败:' + resMeta.message);
						}else if(_this.$i18n.locale=='en'){
							_this.$Message.warning('Failed to load specification data:' + resMeta.message);
						}else if(_this.$i18n.locale=='it'){
							_this.$Message.warning('Impossibile caricare i dati delle specifiche:' + resMeta.message);
						}
						
					}
				});
			},
			/**
			 * 构建SKU 属性
			 */
			buildSkuProperty(product_, data) {
				let specList = data.specs;
				let skuPropertyList = product_.skuPropertyList;
				
				let canDo = true;
				if(specList.length == 0) {
					if(skuPropertyList.length != 0) {
						//目录规格参数发生变更,提示后，进行重置
						canDo = false;
					}
				} else {
					if(skuPropertyList.length == 0) {
						//目录规格参数发生变更,提示后，进行重置
						canDo = false;
					} else if(skuPropertyList[0].length != specList.length){
						canDo = false;
					} else {
						let skuPropertyList0 = skuPropertyList[0];
						for(let i = 0; i < specList.length; i++) {
							let pid = specList[i].page.id;
							let vs = false;
							for(let i = 0; i < skuPropertyList0.length; i++) {
								let pid1 = skuPropertyList0[i].propertyId;
								if(pid == pid1) {
									vs = true;
									break;
								}
							}
							if(!vs) {
								//发生变化，重置
								canDo = false;
								break;
							}
						}
					}
				}
				
				this.buildPropertyData(data);
				if(canDo) {
					//合并
					this.mergeSku(product_.skuList, skuPropertyList, specList);
				}
			},
			/**
			 * 合并结果
			 */
			mergeSku(skuList, skuPropertyList, specList) {
				//合并规格选项的值并且构建SKU表格
				let skuPropertyMap = {};
				for(let i = 0; i < skuPropertyList.length; i++) {
					let skuProperty_ = skuPropertyList[i];
					let skuProperty = skuProperty_[0];
					skuPropertyMap[skuProperty.productSkuId] = skuProperty_;
				}
				
				this.form2.table.datas = [];
				for(let i = 0; i < skuList.length; i++) {
					let sku = skuList[i];
					let skuProperty = skuPropertyMap[sku.id];
					
					let rowData = {};
					//添加规格
					if(skuProperty) {
						let primaryKey = '';
						for(let j = 0; j < skuProperty.length; j++) {
							let skuPropertySingle = skuProperty[j];
							let propertyValue = skuPropertySingle.propertyValue;
							rowData['label' + j] = propertyValue;
							primaryKey += (propertyValue + '_');
							if(this.form2.model.values[j].indexOf(propertyValue) < 0) {
								this.form2.model.values[j].push(propertyValue);
							}
							if(specList[j].values.indexOf(propertyValue) < 0) {
								specList[j].values.push(propertyValue);
							}
						}
						rowData['primaryKey'] = primaryKey;
					}
					rowData['price'] = sku.price;
					rowData['marketPrice'] = sku.marketPrice;
					rowData['stock'] = sku.stock;
					rowData['memberPrice'] = sku.memberPrice;
					this.form2.table.datas.push(rowData);
				}
			},

			/**
			 * 构建规格参数数据
			 */
			buildPropertyData(data) {
				let specList = data.specs;
				this.buildSpecData(specList);
			},
			/**
			 * 构建规格数据
			 */
			buildSpecData(datas_) {
				this.form2.specs = datas_;
				this.initColumns();

				if(datas_.length == 0) {
					//当前商品类型没有配置规格
					this.initDefaultSku();
				}
			},
			/**
			 * 添加默认的SKU
			 */
			initDefaultSku() {
				this.form2.table.datas.push({
					price: 0,
					marketPrice: 0,
					stock: 0,
					primaryKey: '-1'
				});
			},
			/**
			 * 初始化列
			 */
			initColumns() {
				let specColumns = this.initSpecColumns();
				this.form2.table.skuColumns = specColumns;
				this.form2.table.datas = [];
			},
			/**
			 * 初始化规格列
			 */
			initSpecColumns() {
				let specs = this.form2.specs;
				let columns = [];
				this.form2.model.values = [];
				for(let i = 0; i < specs.length; i++) {
					let spec = specs[i].page;
					columns.push({
						title: spec.name,
						key: 'label' + i
					});
					//进行初始化防止直接从后面点击
					this.form2.model.values.push([]);
				}
				return columns;
			},
			/**
			 * 规格选型切换
			 */
			specItemChange(specItem_, specIndex_) {
				let specValues = this.form2.model.values;
				let specs = this.form2.specs;
				let specValueLength = specValues.length;
				let specLength = specs.length;
				if(specValueLength != specLength) {
					//存在选项没有选择的，清空表格
					this.form2.table.datas = [];
					return;
				}
				//构建SKU
				let skus = DescartesUtils.descartes(specValues);
				let skuLength = skus.length;
				if(0 == skuLength) {
					//存在选项没有选择的，清空表格
					this.form2.table.datas = [];
				} else {
					let preDatas = this.form2.table.datas;
					let skuMap = {};
					for(let j = 0; j < preDatas.length; j++) {
						let preData = preDatas[j];
						skuMap[preData.primaryKey] = preData;
					}

					//重新构建
					this.form2.table.datas = [];
					for(let i = 0; i < skuLength; i++) {
						let skuGroups = skus[i];
						let rowData = {};
						let primaryKey = '';
						for(let j = 0; j < skuGroups.length; j++) {
							let suk = skuGroups[j];
							rowData['label' + j] = suk;
							primaryKey += (suk + '_');
						}

						let skuItemData = skuMap[primaryKey];
						let price_ = skuItemData ? skuItemData['price'] : 0;
						let marketPrice_ = skuItemData ? skuItemData['marketPrice'] : 0;
						let stock_ = skuItemData ? skuItemData['stock'] : 0;

						rowData['price'] = price_;
						rowData['marketPrice'] = marketPrice_;
						rowData['stock'] = stock_;
						rowData['primaryKey'] = primaryKey;

						this.form2.table.datas.push(rowData);
					}
				}

			},
			/**
			 * 添加规格值
			 */
			addSpecValue(index) {
				let inputValue = this.form2.model.inputValues[index];
				if(null != inputValue) {
					inputValue = inputValue.trim();
				}
				if(Util.vad.isBlank(inputValue)) {
					return;
				}
				let currentSpecValues = this.form2.specs[index].values;
				//需要判断是否重复
				for(let i = 0; i < currentSpecValues.length; i++) {
					if(inputValue == currentSpecValues[i]) {
						return;
					}
				}
				currentSpecValues.push(inputValue);
				this.form2.model.inputValues[index] = '';
			},

			/**
			 * 第二步-下一步
			 */
			secondNextStep() {
				this.$refs["form1"].validate((valid) => {
					if(valid) {
						//判断SKU是否选择
						if(this.form2.table.datas.length == 0) {
							if(this.$i18n.locale=='zh'){
								this.$Message.info("请至少添加一条规格数据");
							}else if(this.$i18n.locale=='en'){
								this.$Message.info("Please add at least one specification data");
							}else if(this.$i18n.locale=='it'){
								this.$Message.info("Si prega di aggiungere almeno una specifica dati");
							}
							
							return;
						}
						this.current = 2;
						//初始化编辑器
						this.form3.editor.whetherInit = true;
					}
				});
			},
			/**
			 * SKU设置应用到所有
			 */
			skuSettingToAll(index) {
				let dataLength = this.form2.table.datas.length;
				if(dataLength < 2) {
					return;
				}
				let current = this.form2.table.datas[index];
				for(let i = 0; i < dataLength; i++) {
					this.form2.table.datas[i].price = current.price;
					this.form2.table.datas[i].marketPrice = current.marketPrice;
					this.form2.table.datas[i].stock = current.stock;
					this.form2.table.datas[i].memberPrice = current.memberPrice;
				}
			},
			/**
			 * 保存并发布
			 */
			saveAndUpProduct() {
				this.vadSubmitProduct(2);
			},
			/**
			 * 保存商品
			 */
			saveProduct() {
				this.vadSubmitProduct(1);
			},

			/**
			 * 保存商品
			 */
			vadSubmitProduct(action) {
				//2.商品文本描述
				let content = this.$refs.ue.getUEContent();
				if(Util.vad.isBlank(content)) {
					if(this.$i18n.locale=='zh'){
						this.$Message.info("添加商品描述,可以提高商品的曝光度哦~");
					}else if(this.$i18n.locale=='en'){
						this.$Message.info("Add a description of the item to increase the exposure of the item.~");
					}else if(this.$i18n.locale=='it'){
						this.$Message.info("Aggiungi una descrizione dell'articolo per aumentare l'esposizione dell'oggetto.~");
					}
					
					return;
				}
				this.saveAfterVad(action);
			},
			/**
			 * 提交数据
			 */
			saveAfterVad(action) {
				let content = this.$refs.ue.getUEContent();
				let postData_ = {
					action: action,
					product: {
						id: this.form1.model.id,
						name: this.form1.model.name,
						wdesc: content,
						categoryId: this.form0.currentCatelogId,
						promotionStatus: this.form1.model.promotionStatus,
						languageCode: this.form1.model.languageCode,
						brandId: this.form1.model.brandId,
						saleType: this.form1.model.saleType,
						makeFlag: this.form1.model.makeFlag,
						isReturnExchange: this.form1.model.isReturnsExchange
					}
				};
				//SKU
				let skuList = [];
				let skuPropertyList = [];
				let specs = this.form2.specs;
				let specsLength = specs.length;
				let preDatas = this.form2.table.datas;
				for(let i = 0; i < preDatas.length; i++) {
					let sku_ = preDatas[i];
					if(specsLength > 0) {
						let skuPropertyArray = [];
						for(let j = 0; j < specsLength; j++) {
							let pv_ = sku_['label' + j];
							let spec_ = specs[j].page;
							let skuPropertyRow = {
								propertyId: spec_.id,
								propertyValue: pv_,
								orderNum: 1
							};
							skuPropertyArray.push(skuPropertyRow);
						}
						skuPropertyList.push(skuPropertyArray);
					}

					let skuRow = {
						marketPrice: sku_.marketPrice,
						price: sku_.price,
						stock: sku_.stock,
						memberPrice: sku_.memberPrice
					};
					skuList.push(skuRow);
				}

				postData_['skuList'] = skuList;
				postData_['skuPropertyList'] = skuPropertyList;

				this.submitProduct(postData_);
			},
			submitProduct(postData_) {
				const _this = this;
				this.axios.put('/ws/v2/ms/product', postData_).then(function(response) {
					let res = response.data;
					if(0 === res.meta.code) {
						_this.execUploadPic(res.data);
					} else {
						let message_ = res.meta.message;
						if(_this.$i18n.locale=='zh'){
							_this.$Message.warning('添加商品失败:' + message_);
						}else if(_this.$i18n.locale=='en'){
							_this.$Message.warning('Add item failed:' + message_);
						}else if(_this.$i18n.locale=='it'){
							_this.$Message.warning('Aggiungi elemento non riuscito:' + message_);
						}
						
					}
				});
			},
			/**
			 * 执行图片上传
			 */
			execUploadPic(data) {
				this.form4.imgConfig = data;
				let tmpPics = this.form4.tmpPics;
				let result = false;
				for(let i = 0; i < 5; i++) {
					let newFile = this.form4.files[i];
					if(newFile) {
						this.$refs.picUpload[i].execUpload([newFile]);
						result = true;
					} else {
						//直接更新数据库
						if(tmpPics[i] && tmpPics[i].indexOf('http') == 0) {
							this.form4.updateTmpPics.push({
								url: tmpPics[i],
								index: i
							});
						}
					}
				}
				if(!result) {
					this.updateProductPic();
				}
			},
			/**
			 * 更新商品的图片
			 */
			updateProductPic() {
				let updateTmpPics = this.form4.updateTmpPics;
				for(let i = 0; i < updateTmpPics.length; i++) {
					let tmpPic = updateTmpPics[i];
					let response = {
						data: {
							pubFileUrl: tmpPic.url
						}
					};
					this.saveProductImg(response, tmpPic.index);
				}
				this.clearPage();
			},
			
			/**
			 * 清空商品
			 */
			clearPage() {
				if(Util.vad.isBlank(this.form4.imgConfig.primaryPicUrl)) {
					this.result.ok = true;
					return;
				}
				let postData_ = {
					id: this.form4.imgConfig.productId,
					primaryPicUrl: this.form4.imgConfig.primaryPicUrl
				};
				let _this = this;
				this.axios.put('/ws/v2/ms/product/primaryimg', postData_).then(function(response) {
					let res = response.data;
					if(0 === res.meta.code) {
						_this.result.ok = true;
					} else {
						let message_ = res.meta.message;
						if(_this.$i18n.locale=='zh'){
							_this.$Message.warning('新增商品失败:' + message_);
						}else if(_this.$i18n.locale=='en'){
							_this.$Message.warning('New item failed:' + message_);
						}else if(_this.$i18n.locale=='it'){
							_this.$Message.warning('Nuovo elemento fallito:' + message_);
						}
						
					}
				});
				
			},
			goBack() {
				this.$store.dispatch('authHandUpdateMenu', {'router': this.$router, 'curr': {
					name: 'ms_product_list_v2'
				}});
			},
			/**
			 * 上传商品图片
			 */
			picUploadSuccess(response, file, fileList, loopIndex) {
				if(0 == response.meta.code) {
					this.saveProductImg(response, loopIndex);
				}
			},
			/**
			 * 保存图片信息
			 */
			saveProductImg(response, loopIndex) {
				const _this = this;
				let pubFileUrl = response.data.pubFileUrl;
				let imgConfig = this.form4.imgConfig;
				let postData_ = {
					imgId: imgConfig.imgId,
					tenantId: imgConfig.tenantId,
					imgUrl: pubFileUrl,
					orderNum: loopIndex
				};
				if(0 == loopIndex) {
					this.form4.imgConfig.primaryPicUrl = pubFileUrl;
				}
				this.axios.post('/ws/sys/imgs', postData_).then(function(response) {
					let res = response.data;
					if(0 === res.meta.code) {
						//所有图片上传完成后，执行提示任务
						_this.form4.num++;
						if(_this.picNewCount == _this.form4.num) {
							_this.updateProductPic();
						}
						
					} else {
						let message_ = res.meta.message;
						if(_this.$i18n.locale=='zh'){
							_this.$Message.warning('上传图片失败:' + message_);
						}else if(_this.$i18n.locale=='en'){
							_this.$Message.warning('Uploading image failed:' + message_);
						}else if(_this.$i18n.locale=='it'){
							_this.$Message.warning('Caricamento immagine fallito:' + message_);
						}
						
					}
				});
			},
			/**
			 * 获取上传文件列表
			 */
			uploadFileList(fileList, loopIndex) {
				//构建一个新的FILE
				let file_ = fileList[0];
				let tenantId = this.$store.getters.auth_tenantId;
				let fileName = tenantId + '_' + new Date().getTime() + '.' + Util.getFileSuffix(file_.name);
				let newFile = new File([file_], fileName, {type: file_.type});
				this.form4.files[loopIndex] = newFile;
				this.form4.fileNames[loopIndex] = fileName;
				
				//读取本地文件base64
				this.readLocalFile(newFile, loopIndex);
			},
			/**
			 * 读取本地文件
			 */
			readLocalFile(newFile, loopIndex) {
				let _this = this;
				FileUtil.readFile(newFile, function(result, currFile) {
					_this.$set(_this.form4.tmpPics, loopIndex, result);
					console.log(_this.form4.tmpPics);
				});
			},
			/**
			 * 清空所有
			 */
			clearAll() {
				this.current = 0;//当前步骤
				this.isStepOver = false;//是否已经配置规格
				this.preCategoryId = null;//上一次选择的商品类目
				this.form0.groups = [];
				this.form0.indexPaths = [];
				this.form0.isLastLevel = false;
				this.form0.currentCatelogId = null;
				this.form0.labels = [];
				this.form1.model.brandId = '';
				this.form1.model.name = '';
				this.form1.model.promotionStatus = 0;
				this.form1.model.languageCode = '';
				this.form1.model.saleType = 1;
				this.form1.model.makeFlag = 1;
				this.form1.model.isReturnsExchange = 1;
				this.form2.model.values = [];
				this.form2.model.inputValues = [];
				this.form2.table.skuColumns = [];
				this.form2.table.datas = [];
				this.form2.specs = [];
				this.form3.model.wDesc = '';
				this.form4.tmpPics = [];
				this.form4.files = [];
				this.form4.fileNames = [];
				this.form4.num = 0;
				this.form4.imgConfig = {};
				this.result.ok = false;
				
				this.$refs.ue.setUEContent('');
				this.$refs["form1"].resetFields();
				
				let data_ = this.form0.categoryTree;
				this.form0.groups.push({
					datas: data_
				});
			},
			/**
			 * 往右移动
			 */
			movePicRight(index) {
				this.buildArray(this.form4.tmpPics, index, index + 1);
				this.buildArray(this.form4.files, index, index + 1);
				this.buildArray(this.form4.fileNames, index, index + 1);
			},
			buildArray(array_, index1, index2) {
				let tmpPic1 = array_[index1];
				let tmpPic2 = array_[index2];
				this.$set(array_, index1, tmpPic2);
				this.$set(array_, index2, tmpPic1);
			},
			/**
			 * 设置为主图
			 */
			setPicPrimary(index) {
				this.buildArray(this.form4.tmpPics, 0, index);
				this.buildArray(this.form4.files, 0, index);
				this.buildArray(this.form4.fileNames, 0, index);
			},
			/**
			 * 删除当前
			 */
			removePic(index) {
				console.log(this.form4.tmpPics[index]);
				this.form4.tmpPics.splice(index, 1);
				this.form4.files.splice(index, 1);
				this.form4.fileNames.splice(index, 1);
			},
			/**
			 * 往左移动
			 */
			movePicLeft(index) {
				this.buildArray(this.form4.tmpPics, index, index - 1);
				this.buildArray(this.form4.files, index, index - 1);
				this.buildArray(this.form4.fileNames, index, index - 1);
			},
			/**
			 * 价格进行格式化
			 */
			priceFormatter(row) {
				row.price = parseFloat(parseFloat(row.price).toFixed(2));
			},
			/**
			 * 市场价格格式化
			 */
			marketPriceFormatter(row) {
				row.marketPrice = parseFloat(parseFloat(row.marketPrice).toFixed(2));
			}
		}
	}
</script>

<style scoped>
	.ws-form-div-form {
		width: 90%;
	}
	
	.step-data {
		padding-top: 20px;
	}
	/*清除浮动*/
	
	.clearfix:after {
		clear: both;
		display: block;
		height: 0;
		content: "";
	}
	/**选择商品分类**/
	
	.wareSort {
		padding: 15px 8px 15px 7px;
		border: 1px solid #ddd;
		background-color: #f6f6f6;
	}
	
	.wareSort ul {
		float: left;
		width: 290px;
		padding: 10px;
		border: 1px solid #ddd;
		margin-right: 7px;
		margin-left: 8px;
		background-color: #fff;
	}
	
	.wareSort ul li a {
		display: block;
		padding-right: 25px;
		padding-left: 10px;
		border: 1px solid #fff;
		line-height: 28px;
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
	}
	
	.wareSort ul li a:hover {
		color: #52bea6;
	}
	
	.wareSort ul li.active a {
		border-color: #52bea6;
		background: #cefff4 url(../../../assets/images/product/arrow.png) no-repeat right center;
		color: #52bea6;
	}
	
	.selectedSort {
		padding: 10px 15px;
		border: 1px solid #ed7f5a;
		margin-top: 10px;
		margin-bottom: 10px;
		background-color: #fff4f0;
		color: #ed7f5a;
	}
	
	.selectedSort b {
		font-weight: bold;
	}
	
	.selectedSort i font {
		font-family: simsun;
	}
	
	.wareSortBtn {
		text-align: center;
	}
	
	.wareSortBtn button {
		width: 200px;
	}
	
	.upload-list-cover {
		display: none;
        width: 200px;
	    height: 200px;
	    position: relative;
	    bottom: 0;
	    margin-top: -100%;
	    background: rgba(0,0,0,.6);
	    line-height: 200px;
	    text-align: center;
	}
	.primary-pic {
		position: relative;
    	background-color: #ffffff;
    	opacity: 0.8;
    	margin-top: -20%;
	}
	.primary-pic span {
		color: red;
		font-size: 16px;
	}
	.upload-list-cover i {
		color: #fff;
        font-size: 30px;
        cursor: pointer;
        padding-right: 15px;
	}
	.upload-list:hover .upload-list-cover {
		display: block;
	}	
	.img-list {
		list-style:none; /* 去掉ul前面的符号 */
	    margin: 0px; /* 与外界元素的距离为0 */
	    padding: 0px; /* 与内部元素的距离为0 */
	    width: auto; /* 宽度根据元素内容调整 */
	}
	.img-list li {
		float:left; /* 向左漂移，将竖排变为横排 */
		margin: 5px;
		position:relative;
	}
</style>